#!/bin/bash

set -e

# 包信息
PROJECT_NAME="drwtestlinux"
VERSION="1.3"
MAINTAINER="huwenyupeter <huwenyupeter@qq.com>"
DESCRIPTION="存储设备写入可靠性验证测试工具"

# 目录设置
BUILD_DIR="build"
DIST_DIR="dist"
TOOLCHAIN_DIR="cmake"

# 创建构建目录
mkdir -p ${BUILD_DIR}

# 清理之前的构建
rm -rf ${BUILD_DIR}/*

echo "=== 在Kali Linux上构建 ${PROJECT_NAME} v${VERSION} ==="

# 检查并安装必要的工具
echo "检查必要的工具..."
if ! command -v cmake &> /dev/null; then
    echo "安装cmake..."
    sudo apt-get update
    sudo apt-get install -y cmake
fi

if ! command -v pkg-config &> /dev/null; then
    echo "安装pkg-config..."
    sudo apt-get update
    sudo apt-get install -y pkg-config
fi

if ! command -v aarch64-linux-gnu-gcc &> /dev/null; then
    echo "安装aarch64交叉编译工具链..."
    sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
fi

# 函数：构建指定架构
build_architecture() {
    local arch=$1
    local toolchain=$2
    local build_dir="${BUILD_DIR}/${arch}"
    
    echo "构建 ${arch} 架构..."
    
    mkdir -p ${build_dir}
    cd ${build_dir}
    
    # 配置CMake
    cmake ../.. \
        -DCMAKE_TOOLCHAIN_FILE=../../${TOOLCHAIN_DIR}/${toolchain} \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_INSTALL_PREFIX=/usr
    
    # 编译
    make -j$(nproc)
    
    cd ../..
    
    echo "${arch} 构建完成"
    
    # 显示构建结果
    echo "构建结果: ${build_dir}/${PROJECT_NAME}"
    if [ -f "${build_dir}/${PROJECT_NAME}" ]; then
        ls -la "${build_dir}/${PROJECT_NAME}"
        echo "✅ ${arch} 架构构建成功"
    else
        echo "❌ ${arch} 架构构建失败"
        return 1
    fi
}

# 构建x86_64版本
echo "开始构建x86_64版本..."
if build_architecture "x86_64" "toolchain-x86_64.cmake"; then
    echo "x86_64版本构建成功"
else
    echo "x86_64版本构建失败"
fi

# 构建aarch64版本
echo "开始构建aarch64版本..."
if command -v aarch64-linux-gnu-gcc &> /dev/null; then
    if build_architecture "aarch64" "toolchain-aarch64.cmake"; then
        echo "aarch64版本构建成功"
    else
        echo "aarch64版本构建失败"
    fi
else
    echo "警告: 未找到aarch64交叉编译工具链，跳过ARM64构建"
    echo "安装命令: sudo apt-get install gcc-aarch64-linux-gnu g++-aarch64-linux-gnu"
fi

echo "=== 构建完成 ==="
echo "构建结果位于: ${BUILD_DIR}/"
find ${BUILD_DIR} -name "${PROJECT_NAME}" -type f 2>/dev/null || echo "未找到可执行文件"

# 显示使用说明
echo ""
echo "使用说明:"
echo "运行x86_64版本: ./${BUILD_DIR}/x86_64/${PROJECT_NAME}"
echo "运行aarch64版本: ./${BUILD_DIR}/aarch64/${PROJECT_NAME}"